package cn.com.dingtek.genius.manager.server.web.controller;

import cn.com.dingtek.genius.manager.server.event.UserOperateEvent;
import cn.com.dingtek.genius.manager.server.repository.db.entity.AuthRule;
import cn.com.dingtek.genius.manager.server.service.AuthRuleService;
import cn.com.dingtek.genius.manager.server.support.sam.SecurityContextHolder;
import cn.com.dingtek.genius.manager.server.support.sam.annotation.AssertAuth;
import cn.com.dingtek.genius.manager.server.utils.IPUtil;
import cn.com.dingtek.genius.manager.server.web.Result;
import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/auth/rule")
public class AuthRuleController {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private AuthRuleService authRuleService;

    @AssertAuth
    @PostMapping("/list")
    public Result list(@RequestBody JSONObject json) {
        int currentPage = json.getInteger("current_page") == null ? 0 : json.getInteger("current_page");
        int pageSize = json.getInteger("page_size") == null ? 10 : json.getInteger("page_size");
        AuthRule param = json.getObject("search_param", AuthRule.class);

        Long groupId = json.getJSONObject("search_param").getLong("groupId");
        return Result.ok(authRuleService.list(param, groupId, currentPage, pageSize));
    }

    @AssertAuth
    @PostMapping("/add")
    public Result add(@RequestBody JSONObject json, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        AuthRule param = json.toJavaObject(AuthRule.class);
        try {
            authRuleService.add(param, DateTime.now().toDate());
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("新增权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("新增权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        return Result.ok(authRuleService.info(id));
    }

    @AssertAuth
    @PostMapping("/update")
    public Result update(@RequestBody JSONObject json, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        AuthRule param = json.toJavaObject(AuthRule.class);
        try {
            authRuleService.update(param, DateTime.now().toDate());
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("修改权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("修改权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/remove/{id}")
    public Result remove(@PathVariable("id") Long id, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        try {
            authRuleService.remove(id);
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("删除权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("权限管理")
                    .setOperateDesc("删除权限")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }
}
